<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useDealer } from "./utils/hook";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Delete from "~icons/ep/delete";
import EditPen from "~icons/ep/edit-pen";
import Refresh from "~icons/ep/refresh";
import AddFill from "~icons/ri/add-circle-line";
import { ElMessageBox, type FormInstance, type FormRules } from "element-plus";
import { getIsSealed } from "@/utils/auth";
import { useUserStoreHook } from "@/store/modules/user";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";
import { message } from "@/utils/message";
defineOptions({
  name: "SystemDealer"
});
const handleDeleteConfirm = (row: any) => {
  ElMessageBox.confirm(
    `是否确认删除经销商名称为${row.Name}的这条数据`,
    "确认删除",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }
  )
    .then(() => {
      handleDelete(row);
    })
    .catch(() => {
      // 用户取消删除操作
    });
};
const tableRef = ref();
const formRef = ref();

const {
  form,
  loading,
  columns,
  dataList,
  treeData, // 引入树形数据
  selectedNum,
  pagination,
  deviceDetection,
  statisticsData,
  getStatisticsData,
  onSearch,
  resetForm,
  onbatchDel,
  openDialog,
  handleDelete,
  handleSizeChange,
  onSelectionCancel,
  handleCurrentChange,
  handleSelectionChange
} = useDealer(tableRef);
// 修改密码对话框相关变量和方法
const passwordDialogVisible = ref(false);
const currentDealerInfo = ref(null);
const passwordFormRef = ref<FormInstance>();
const passwordForm = ref({
  newPassword: "",
  confirmPassword: ""
});

// 密码验证规则
const passwordRules: FormRules = {
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 6, message: "密码长度至少6位", trigger: "blur" },
    {
      pattern: /^[0-9a-zA-Z!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~`]+$/,
      message: "密码只能包含数字、字母和普通符号，不允许空格",
      trigger: "blur"
    }
  ],
  confirmPassword: [
    { required: true, message: "请确认密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
};

// 打开修改密码对话框
const openPasswordDialog = row => {
  currentDealerInfo.value = row;
  passwordForm.value = {
    newPassword: "",
    confirmPassword: ""
  };
  passwordDialogVisible.value = true;
};

// 关闭修改密码对话框
const closePasswordDialog = () => {
  passwordDialogVisible.value = false;
  // 清除表单验证状态
  passwordFormRef.value?.clearValidate();
};

// 提交修改密码
const submitPasswordChange = async () => {
  // 表单验证
  if (!passwordFormRef.value) return;

  try {
    await passwordFormRef.value.validate();

    // 调用修改密码接口
    const id = currentDealerInfo.value.Id;
    const pwd = passwordForm.value.newPassword;
    const params = {
      id: id,
      pwd: passwordForm.value.newPassword
    };

    const result = await http.request(
      "put",
      changeHttpLink(`/api/System/${id}/change_pwd`),
      {
        params: {
          id: id,
          pwd: pwd
        }
      }
    );
    console.log("result", result);
    if (result.Success) {
      message("密码修改成功", { type: "success" });
      closePasswordDialog();
    } else {
      message(result.Message || "密码修改失败", { type: "error" });
    }
  } catch (error) {
    console.error("修改密码失败:", error);
    message("密码修改失败，请重试", { type: "error" });
  }
};

onMounted(() => {
  // 打印缓存的IsSealed
  console.log("IsSealed缓存状态:", getIsSealed());
  console.log("登录缓存", useUserStoreHook());
});
</script>

<template>
  <div class="system-dealer-container">
    <!-- 统计信息展示区域 -->
    <div class="bg-white p-6 rounded-lg shadow-sm mb-6">
      <div class="grid grid-cols-1 md:grid-cols-3 gap-4 text-center">
        <div class="p-4 border rounded-lg">
          <p class="text-gray-500 mb-1">子经销数/可创建数</p>
          <p class="text-2xl font-bold text-blue-600">
            {{ statisticsData.subCount }}/{{ statisticsData.subLimit }}
          </p>
        </div>
        <div class="p-4 border rounded-lg">
          <p class="text-gray-500 mb-1">租户数/可创建数</p>
          <p class="text-2xl font-bold text-blue-600">
            {{ statisticsData.tenantCount }}/{{ statisticsData.tenantLimit }}
          </p>
        </div>
        <div class="p-4 border rounded-lg">
          <p class="text-gray-500 mb-1">月卡总数/月卡可用数</p>
          <p class="text-2xl font-bold text-blue-600">
            {{ statisticsData.monthCardTotal }}/{{
              statisticsData.monthCardAvailable
            }}
          </p>
        </div>
      </div>
    </div>

    <div :class="['flex', 'justify-between', deviceDetection() && 'flex-wrap']">
      <div :class="[deviceDetection() ? ['w-full', 'mt-2'] : 'w-[calc(100%)]']">
        <el-form
          ref="formRef"
          :inline="true"
          :model="form"
          class="search-form bg-bg_color w-full pl-8 pt-[12px] overflow-auto"
        >
          <el-form-item label="经销商名称" prop="Name">
            <el-input
              v-model="form.Name"
              placeholder="请输入经销商名称"
              clearable
              class="w-[180px]!"
            />
          </el-form-item>
          <el-form-item label="经销商编码" prop="Code">
            <el-input
              v-model="form.Code"
              placeholder="请输入经销商编码"
              clearable
              class="w-[180px]!"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              :icon="useRenderIcon('ri/search-line')"
              :loading="loading"
              @click="onSearch"
            >
              搜索
            </el-button>
            <el-button
              :icon="useRenderIcon(Refresh)"
              @click="resetForm(formRef)"
            >
              重置
            </el-button>
          </el-form-item>
        </el-form>

        <PureTableBar title="" :columns="columns" @refresh="onSearch">
          <template #buttons>
            <el-button
              type="primary"
              :icon="useRenderIcon(AddFill)"
              @click="openDialog('创建', '')"
            >
              新增经销商
            </el-button>
          </template>
          <template v-slot="{ size, dynamicColumns }">
            <div
              v-if="selectedNum > 0"
              v-motion-fade
              class="bg-[var(--el-fill-color-light)] w-full h-[46px] mb-2 pl-4 flex items-center"
            >
              <div class="flex items-center gap-4">
                <span
                  style="font-size: var(--el-font-size-base)"
                  class="text-[rgba(42,46,54,0.5)] dark:text-[rgba(220,220,242,0.5)]"
                >
                  已选 {{ selectedNum }} 项
                </span>
                <el-button type="primary" text @click="onSelectionCancel">
                  取消选择
                </el-button>
                <el-popconfirm title="是否确认删除?" @confirm="onbatchDel">
                  <template #reference>
                    <el-button type="danger" text> 批量删除 </el-button>
                  </template>
                </el-popconfirm>
              </div>
            </div>
            <pure-table
              ref="tableRef"
              row-key="Id"
              adaptive
              :adaptiveConfig="{ offsetBottom: 108 }"
              align-whole="center"
              table-layout="auto"
              :loading="loading"
              :size="size"
              :data="treeData"
              :columns="dynamicColumns"
              :pagination="{ ...pagination, size }"
              :header-cell-style="{
                background: 'var(--el-fill-color-light)',
                color: 'var(--el-text-color-primary)'
              }"
              @selection-change="handleSelectionChange"
              @page-size-change="handleSizeChange"
              @page-current-change="handleCurrentChange"
            >
              <!-- 添加树形名称的slot -->
              <template #treeName="{ row }">
                <span
                  :style="{ paddingLeft: ((row.Level || 1) - 1) * 5 + 'px' }"
                >
                  {{ row.Name }}
                </span>
              </template>
              <template #operation="{ row }">
                <el-button
                  class="reset-margin"
                  link
                  type="primary"
                  :size="size"
                  :icon="useRenderIcon(EditPen)"
                  @click="openDialog('修改', row)"
                >
                  修改
                </el-button>
                <el-dropdown :hide-on-click="false">
                  <el-button
                    class="ml-3! mt-[2px]!"
                    link
                    type="primary"
                    :size="size"
                    :icon="useRenderIcon('ep:more')"
                  />
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item>
                        <div>
                          <el-button
                            class="reset-margin"
                            link
                            type="primary"
                            :size="size"
                            :icon="useRenderIcon(Delete)"
                            @click.stop="handleDeleteConfirm(row)"
                          >
                            删除
                          </el-button>
                        </div>
                      </el-dropdown-item>
                      <!-- 修改经销商密码 -->
                      <el-dropdown-item>
                        <div>
                          <el-button
                            class="reset-margin"
                            link
                            type="primary"
                            :size="size"
                            :icon="useRenderIcon('ep:key')"
                            @click.stop="openPasswordDialog(row)"
                          >
                            修改密码
                          </el-button>
                        </div>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </template>
            </pure-table>
          </template>
        </PureTableBar>
      </div>
    </div>

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="修改密码"
      width="35%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="password-dialog-content">
        <el-form
          ref="passwordFormRef"
          :model="passwordForm"
          :rules="passwordRules"
          label-width="100px"
        >
          <el-form-item label="新密码:" prop="newPassword">
            <el-input
              v-model="passwordForm.newPassword"
              type="password"
              placeholder="请输入新密码 (至少6位，数字字母符号，不含空格)"
              show-password
              maxlength="50"
            />
          </el-form-item>
          <el-form-item label="确认密码:" prop="confirmPassword">
            <el-input
              v-model="passwordForm.confirmPassword"
              type="password"
              placeholder="请再次输入新密码"
              show-password
              maxlength="50"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closePasswordDialog">取消</el-button>
          <el-button type="primary" @click="submitPasswordChange"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
export default {};
</script>

<style scoped>
.password-dialog-content {
  padding: 20px 0;
}
</style>
<style lang="scss" scoped>
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}

:deep(.el-button:focus-visible) {
  outline: none;
}

.main-content {
  margin: 24px 24px 0 !important;
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}

// 设置分页组件左对齐
:deep(.el-pagination) {
  justify-content: flex-start !important;
}

// 设置按钮容器左对齐
:deep(.flex.justify-between.w-full.h-\[60px\].p-4) {
  justify-content: flex-start !important;

  .flex.items-center.justify-around {
    justify-content: flex-start !important;
    margin-left: 0 !important;
  }
}
</style>
